package my.service;

import com.jfinal.plugin.activerecord.ActiveRecordException;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import my.model.Message;
import my.model.User;

import java.util.List;

/**
 * Created by Administrator on 2017/4/20 0020.
 */

public class MessageService {

    public void createMessage(User user, Message message) throws ServiceException {
        throw new RuntimeException("未完成");
    }

    public void editMessage(Message message) {
        //TODO:编辑留言
        throw new RuntimeException("未完成");
    }


    public boolean deleteMessageById(int userId, int id) {
        //TODO:删除留言
        boolean ret = true;
        try {
            Db.update("delete from message where user_id = ? and id =?", userId, id);
        } catch (ActiveRecordException e) {
            e.printStackTrace();
            ret = false;
        }
        return ret;
    }

    public List<Message> getAllMessage() {
        //TODO:获得所有留言表记录
        List<Message> messages = Message.dao.find("SELECT * FROM message");
        return messages;
    }

    public List<Record> getAllMessageDetailRecord() {
        //TODO:获得所有留言详情 使用
        List<Record> messageRecords = Db.find("SELECT * from message_detail_view");

        return messageRecords;
    }

    public List<Message> getAllMessageDetail() {
        //TODO:获得所有留言详情 使用视图
        List<Message> messages = Message.dao.find("SELECT message.*, user.username,user.nickname FROM message INNER JOIN user ON user.id = message.user_id");
        return messages;
    }

    public Page<Message> paginateAllMessageDetail(int page, int pageSize) {
        //TODO:获得所有留言详情 使用视图
        Page<Message> messagePage = Message.dao.paginate(page, pageSize, "SELECT message.*, user.username,user.nickname",
                "FROM message INNER JOIN user ON user.id = message.user_id ORDER BY message.id");
        return messagePage;
    }


    public List<Message> getMessageByAuthor(User u) {
        //TODO:根据作者获得所有留言
        throw new RuntimeException("未完成");
    }

    public Message getMessageById(int id) {
        return Message.dao.findById(id);
    }


    public boolean updateMessage(Message message) {
        boolean ret = false;
        try {
            message.update();
            ret = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

}
